package com.richman.ps38;


import jdk.incubator.http.HttpClient;
import jdk.incubator.http.HttpClient.Version;
import jdk.incubator.http.HttpRequest;
import jdk.incubator.http.HttpResponse;



import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLParameters;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.*;
import java.nio.charset.Charset;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;
import java.text.SimpleDateFormat;
import java.time.Duration;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;

import org.eclipse.swt.browser.Browser;
import org.json.*;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.richman.controller.NegativeRatioClient;
import com.richman.ps38.entity.BetAdyData;
import com.richman.ps38.entity.Event;
import com.richman.utils.Common;
import com.richman.utils.SoundThread;



/**
 * Created by bgt on 2017/10/1.
 * Java9http示例
 * <p>
 * VM 参数中添加模块支持
 * --add-modules jdk.incubator.httpclient
 */




public class PS38Http {
	

    HttpClient client = null;

    CookieManager cookieManager = new CookieManager();
    
    
    boolean hasLang = false;
    
    long canGetMainPageTime = -1;
    
    long canGetBalanceTime = -1;
    
    long canGetGameResultTime = -1;
    
    
    //-1 最初状态  ,  0 prepareLogin成功, 1 get main page success, 2 登录成功, -2 登录失败,  3抓取成功, -3抓取失败
    int statusCode = -1;
    
    
    
    Vector<Event> ps38Events = new Vector<Event>();
    
    
    
    private String currenteventid = "";
    private String currentbettype = "";
    private String currenttypedetail = "";
    private String currentpankouarg = "";
    
    long lastFailedTime = -1;
    int continueFailedTimes = 0;
    long canloginTime = 0;
    
    
    
    String ADDRESS = "https://www.ps3838.com/";
    String ACCOUNT = "";
    String PWD = "";
    
     {
    	 
    	 init();
     
     }
     
     public long getCanGetMainPageTime() {
    	 return canGetMainPageTime;
     }
     
     
 	public long getCanGetBalanceTime() {
		return canGetBalanceTime;
	}
 	
 	public long getCanGetResultTime() {
 		return canGetGameResultTime;
 	}
 	
 	public long getCanLoginTime() {
 		return canloginTime;
 	}
     
     public int getStatusCode() {
    	 

    	 return statusCode;
     }
     
     
     public void updateStatusCode(int i) {
    	 
    	 if(statusCode == -1 && i == 0) {
    		 canGetMainPageTime = System.currentTimeMillis() + 10*1000;
    	 }else if(i == 0) {
    		 canGetMainPageTime = System.currentTimeMillis() + 20*1000;
    	 }
    	 
    	 
    	 
     	if(statusCode != 2) {
    		NegativeRatioClient.showtext += Common.getcurrentTimeStr() + ":PS38登陆中...\n";
    		NegativeRatioClient.mainWnd.updateMainWndPS38StatusText(0, ACCOUNT + "登陆中");
    	}
    	
    	if(statusCode != 2 && i == 2) {
    		NegativeRatioClient.showtext += Common.getcurrentTimeStr() + ":PS38登录成功\n";
    		continueFailedTimes = 0;
    	}
    	 
    	
    	if(i==2) {
    		canGetBalanceTime = System.currentTimeMillis() + 30*1000;
    		
    		NegativeRatioClient.mainWnd.updateMainWndPS38StatusText(1, ACCOUNT + "   "+ "在线");
    		
    	}
    	
    	
    	if(i == -1) {
    		//发出声音
    		
    		NegativeRatioClient.mainWnd.updateMainWndPS38StatusText(0, "掉线");
    		
    		if(SoundThread.inPlay == false){
				SoundThread st = new SoundThread();
				SoundThread.status = 2;
				st.start();
			}
    		
    		
    		
    		
    		if(System.currentTimeMillis() - lastFailedTime < 5*60*1000) {
    			continueFailedTimes++;
    		}
    		
    		if(continueFailedTimes > 3) {
    			canloginTime = System.currentTimeMillis() + (continueFailedTimes - 2) * 60*1000;
    		}
    		
    		lastFailedTime = System.currentTimeMillis();
    		
    		
    	}
    	
    	
    	if(statusCode != i) {
    		System.out.println("PS38 HTTP状态更新" + "update ps38_statusCode from " +   Integer.toString(statusCode) + " to " + Integer.toString(i));
    	}
    	 
    	 
    	NegativeRatioClient.mainWnd.updatePS38AccountStatus(ACCOUNT, statusCode);
    	 
    	 statusCode = i;
     }
     
     
     public void prepareLogin() {
    	 String res = HttpGet();
    	 
    	 if(res.toLowerCase().contains("name=\"robots\"")) {
    		 updateStatusCode(0);
    	 }else if(res.contains("htmlMainclass")) {
    		 updateStatusCode(1);
    	 }
    	 
     }
     
     public void getMainPage() {
    	 
    	 String res = HttpGet();
    	 
    	 if(res.contains("htmlMainclass")) {
    		 updateStatusCode(1);
    	 }else if(res.toLowerCase().contains("name=\"robots\"")) {
    		 updateStatusCode(0);
    	 }
    	 
     }
     
     
     public  void setLoginParams(String address, String account, String pwd){
			
			ADDRESS = address;
			ACCOUNT = account;
			PWD = pwd;
	}
     



    public  void init(){
        try {
//            Authenticator authenticator=new Authenticator() {
//            };

            X509TrustManager x509m = new X509TrustManager() {  
            	  
                @Override  
                public X509Certificate[] getAcceptedIssuers() {  
                    return null;  
                }  
          
                @Override  
                public void checkServerTrusted(X509Certificate[] chain,  
                        String authType) throws CertificateException {  
                }  
          
                @Override  
                public void checkClientTrusted(X509Certificate[] chain,  
                        String authType) throws CertificateException {  
                }  
            };  
            // 获取一个SSLContext实例  
            SSLContext s = SSLContext.getInstance("SSL");  
            // 初始化SSLContext实例  
            s.init(null, new TrustManager[] { x509m },  
                    new java.security.SecureRandom());  
            
            
            
            
            
            
            
            
        client= HttpClient.newBuilder()
                //.authenticator(authenticator)//配置authenticator
                .sslContext(s)//配置 sslContext
                .sslParameters(new SSLParameters())//配置 sslParameters
//                .sslParameters(new SSLParameters(new String[] { "TLS_RSA_WITH_AES_128_CBC_SHA" },
//                        new String[] { "TLSv1.2" }))//配置 sslParameters
                .proxy(ProxySelector.getDefault())//配置 proxy
                .executor(Executors.newCachedThreadPool())//配置 executor
                .followRedirects(HttpClient.Redirect.ALWAYS)//配置 followRedirects
                .cookieHandler(cookieManager)//配置 cookieManager
                .version(HttpClient.Version.HTTP_2)//配置 version
                .build();

    } catch (Exception e) {
        e.printStackTrace();
    }
    }
    /**
     * 普通get方式
     *
     *
     * 结果:{
     "msg" : "未查询到用户,请认真检查账户或者是否登录",
     "success" : false
     }
     响应码:200

     */
    public  String HttpGet() {
    	
    	
    	
    	try {
    		
    		
            HttpRequest request = HttpRequest
                    //.newBuilder(URI.create("http://hga020.com/"))
                    .newBuilder(URI.create(ADDRESS + "zh-cn/"))
                    //.header("Host", "www.ps3838.com")//携带的参数
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("Upgrade-Insecure-Requests", "1")
                    .header("Pragma", "no-cache")
                    .header("Cache-Control", "no-cache")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(30))//2秒过期
                    .GET()
                    .build();
            
            
            
            
            
            
            
//            CookieStore cookieJar = cookieManager.getCookieStore();
//            List<HttpCookie> cookies = cookieJar.getCookies();
            
            
            
//            System.out.println("current cookies:");
//            
//            for (HttpCookie cookie : cookies) {
    //
//              System.out.println(cookie);
//            }
//          
            

            
            return getReponse(request);
    		
    	}catch(Exception e) {
    		
    		e.printStackTrace();
    	}
    	

    	return "";

        

    }
    
    public String getAccount() {
    	return ACCOUNT;
    }

    
    

    
    public boolean Login() {

   
        try {
        	
        	
        	String loginstr = "loginId=" + ACCOUNT + "&password=" + PWD;
        	
        	
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(ADDRESS + "member-service/v2/login?locale=zh_CN"))
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Referer", "https://www.ps3838.com/zh-cn/")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(10))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString(loginstr))
                    .build();


            
            
            String res = getReponse(request);
            
            
            if(res.equals("1") || res.equals("3") || res.equals("6")) {            	
            	updateStatusCode(2);            	
            	return true;
            }else if(res.equals("0")) {
            	updateStatusCode(-2);
            }
            
            
            
            return false;
        	
        }catch(Exception e) {
        	e.printStackTrace();
        }
        

        return false;

    }
    
    
    
    
    public void freshOdds() {
    	
    }
    
    
    



    /**
     * 输出响应结果
     * @param request
     * @throws IOException
     * @throws InterruptedException
     */
    public  String getReponse(HttpRequest request) {
    	
    	
    	
    	
    	
    	try {
    		
    		
    		
    		
    		
            HttpResponse<String> response = null;
            
            if (client==null) {
                init();
            }
            response = client.send(request, HttpResponse.BodyHandler.asString(Charset.forName("UTF-8")));
            
            
            if(response == null) {
            	return "";
            }
            
            //String result = response.body();
            
            String result = "";
    		
    		result = new String(response.body().getBytes(Charset.forName("UTF-8")));

    		//System.out.println(response.headers().toString());

    		if(result!= null && result.contains("Your session has timed out")) {
    			updateStatusCode(-1);
    		}
    		
    		
            int code = response.statusCode();
            if (code == 200) {
                //System.out.println("结果:" + result);
                
                //System.out.println("response version:" + response.version());
                
            }
            
            
            //System.out.println("响应码:" + code);
            
            return result;
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    		
    		return e.toString();
    		
    	}
    	
    	
    	

    }
    
    
    
    
    public Map<String ,String> dobet(Map<String, String> oddUpdRes, int betgold) {
    	
    	Map<String ,String> resmap = new HashMap<String, String>();
    	
    	String betres = "";
    	
    	SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	
    	long startbettime = System.currentTimeMillis();
    	
    	try {
    		
    		//Map<String, String> res = updatePS38Ratio(betid,eventid, bettype, typedetail, pankouarg);
    		
    		//bet-placement/buyV2?uniqueRequestId=e77bfc70-315f-9709-d5ba-e5febd28524e&locale=zh_CN
    		
    		String url = ADDRESS + "bet-placement/buyV2?uniqueRequestId=" + generateUUID() + "&locale=zh_CN";
    		
    		
    		
    		
    		
    		
    		
    		JSONArray ja = new JSONArray();
    		
    		JSONObject jb = new JSONObject();
    		
    		jb.put("stake", betgold);
    		jb.put("selectionId", oddUpdRes.get("selectionId"));
    		jb.put("stake", betgold);
    		jb.put("odds", oddUpdRes.get("ratio"));
    		jb.put("wagerType", "NORMAL");
    		jb.put("uniqueRequestId", generateUUID());

    		ja.put(jb);
    		
    		JSONObject jb1 = new JSONObject();
    		jb1.put("oddsFormat", 4);
    		jb1.put("selections", ja);
    		
    		

    		
    		
    		
    		
    		
    		
    		System.out.println(dfSec.format(System.currentTimeMillis()) + "ps38 dobet request str:" + jb1.toString());
    		
    		
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type","application/json")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(30))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString(jb1.toString()))
                    .build();
    		
            
            
    		
            betres = getReponse(request);
            
            System.out.println(dfSec.format(System.currentTimeMillis()) + "~~~~~~~~~~~~~~~ps38 dobet betres:" + betres);
            
            
            //Map<String, String> checkrestmp = requestTimeoutBetCheck(startbettime);
            
            
            //TODO: 检查投注进单以及待确认注单， 看有没有办法检查出具体状态
    		if(betres.contains("request timed out")) {
    			
    			Thread.sleep(2000);
    			
    			Map<String, String> checkres = requestTimeoutBetCheck(startbettime);
    			
    			if(checkres == null) {
            		Common.logOut("投注超时，注单状态暂时无法确认, 返回");
                	resmap.put("status", "-4");
                	return resmap;
    			}
    			
    			if(checkres.get("status").equals("0")||checkres.get("status").equals("1")) {
    				
    				Common.logOut("注单超时已确认，进单返回结果");
    				
    				checkres.put("eventId", oddUpdRes.get("selectionId").split("\\|")[2]);
    				return checkres;
    			}
    			
    			
    			
    			if(checkres.get("status").equals("-1")) {
    				
    				Common.logOut("注单超时已确认，未进单，补单");
    				
    				betres = "PROCESSED_WITH_ERROR";
    			}
    			

    		}
            
            
            
            
            if(betres.contains("ACCEPTED")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "1");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	//resmap.put("betgold", Double.toString(resjb.getDouble("risk")));
            	
            	return resmap;
            }else if(betres.contains("PENDING_ACCEPTANCE")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "0");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	return resmap;
            	
            }
            
            
            
            
            
            
            
        	//start rebet
        	

            if(betres.contains("PROCESSED_WITH_ERROR")) {
        		Common.logOut("------------------------------------ps38 开始补单------------------------------------------------------------------");
        		
        		long startrebettime = System.currentTimeMillis();
        		
        		resmap.put("rebet", "1");
        		
        		
        		while(System.currentTimeMillis() - startrebettime < NegativeRatioClient.mainWnd.getRebetTime()*1000) {
        			
            		String sid = oddUpdRes.get("selectionId");
                    String eventid = sid.split("\\|")[2];
                    
                    ps38Events.clear();
                    
                    updateMatches(eventid);
                    
                    if(ps38Events.size() == 0) {
                    	
                    	Common.logOut("补单抓取总数据失败");
                    	
                    	Thread.sleep(2000);
                    	
                    	continue;
                    }
                    
//                    String betpankoustr = "";
//                    
//                    if(currenttypedetail.contains("主")) {
//                    	betpankoustr = Double.toString(0.0-Double.parseDouble(currentpankouarg));                    	
//            		}else {
//            			betpankoustr = currentpankouarg;
//            		}
                    
                    String betid = "";
                    
                    
                    for(int i = 0; i < ps38Events.size(); i++) {
                    	Common.logOut(ps38Events.elementAt(i).toString());
                    	
                    	Event event = ps38Events.elementAt(i);
                    	
                    	if(currentbettype.contains("全场让球")) {
                    		if(Math.abs(Double.parseDouble(currentpankouarg) - Double.parseDouble(event.wholerqppankou)) < 0.01) {
                    			betid = event.wholeRQPBetID;
                    			break;
                    		}
                    	}else if(currentbettype.contains("全场大小")) {
                    		if(Math.abs(Double.parseDouble(currentpankouarg) - Double.parseDouble(event.wholeDXPPankou)) < 0.01) {
                    			betid = event.wholeDXPBetID;
                    			break;
                    		}
                    	}
                    	
                    }

                    if(betid.equals("")) {
                    	Common.logOut("补单，已经无投注盘口");
                    	Thread.sleep(3000);
                    }else {
                    	
                    	Map<String, String> ps38oddUpdres = updatePS38Ratio(betid, eventid, currentbettype, currenttypedetail, currentpankouarg);
                    	
                    	if(ps38oddUpdres == null) {
                    		Common.logOut("补单，赔率更新失败");
                    		Thread.sleep(2000);
                    	}else {
                    		
                    		Map<String, String> rebetres = rebet(ps38oddUpdres,betgold);
                    		
                    		if(rebetres.get("status").equals("1") || rebetres.get("status").equals("0") || rebetres.get("status").equals("-4")) {
                    			
                    			if(!rebetres.containsKey("eventId")) {
                    				
                    				rebetres.put("eventId", oddUpdRes.get("selectionId").split("\\|")[2]);
                    				
                    			}
                    			
                    			Common.logOut("补单，补单成功");
                    			
                    			rebetres.put("rebet", "1");
                    			
                    			return rebetres;
                    		}else {
                    			Thread.sleep(3000);
                    		}
                    		
                    	}
                    	
                    	
                    	
                    }
                    
        			
        		}
        		

                
                
        		Common.logOut("------------------------------------ps38 补单结束， 失败------------------------------------");
            }
            
        		


        	
        	
        	//end
            
            
            
            
            
            
            
    	}catch(Exception e) {
    		
    		
    		e.printStackTrace();
    		
    		resmap.put("status", "-1");

        	return resmap;

    	}
    	

    	
    	System.out.println(dfSec.format(System.currentTimeMillis()) + "   ps38投注失败:" + betres);

    	resmap.put("status", "-1");
    	
    	return resmap;
    	
    }
    
    
   
    
    
    
    
    
    

    
    public Map<String, String> updatePS38Ratio(String betid, String eventid, String bettype, String typedetail, String pankouarg) {
    	
    	String res = "";
    	typedetail = bettype;
        currenteventid = eventid;
        currentbettype = bettype;
        currenttypedetail = typedetail;
        currentpankouarg = pankouarg;
    	
    	
    	try {
    		
    		//selectionData: [{"selectionId":"556778348|885420736|0|2|0|0|-0.25|0","oddsFormat":1,"oddsId":"885420736|0|2|0|0|-0.25|0"}]
    		
    		//selectionId : "betid|eventid|whole(0)/half(1)|R(2)O(3)|主客场(0,1)/大小球(3,4)|0|pankou|主客(0)/大小(1)"
    		//oddsFormat : 2
    		//oddsId: eventid|whole(0)/half(1)|R(2)O(3)|主客场(0,1)/大小球(3,4)|0|pankou|主客(0)/大小(1)
    		
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		
    		String pankou = pankouarg;
    		
    		if(typedetail.contains("主")) {
    			pankou = Double.toString(0.0-Double.parseDouble(pankouarg));
    		}
    		
    		
    		
    		
    		
//    		boolean isWhole = false;
//    		
//    		if(bettype.contains("全场")) {
//    			isWhole = true;
//    		}
//    		
//    		
//    		betid = getBetidByEventid(eventid, isWhole);
    		
    		if(betid.equals("")) {
    			return null; 
    		}
    		
    		JSONObject jb = new JSONObject();
    		
    		
    		String fakebetid = Long.toString(Long.parseLong(betid) + 1);
    		
    		
    		String selectionId = betid + "|" + eventid;
    		String oddsId = eventid;
    		
    		if(bettype.contains("全场")) {
    			selectionId = selectionId + "|" + "0";
    			oddsId = oddsId + "|" + "0";
    		}else {
    			selectionId = selectionId + "|" + "1";
    			oddsId = oddsId + "|" + "1";
    		}
    		
    		if(bettype.contains("让球")) {
    			selectionId = selectionId + "|" + "2";
    			oddsId = oddsId + "|" + "2";
    		}else {
    			selectionId = selectionId + "|" + "3";
    			oddsId = oddsId + "|" + "3";
    		}
    		
    		if(typedetail.contains("主")) {
    			selectionId = selectionId + "|" + "0|0|" +  pankou + "|0";
    			oddsId = oddsId + "|" + "0|0|" +  pankou + "|0";
    		}else if(typedetail.contains("客")){
    			selectionId = selectionId + "|" + "1|0|" +  pankou + "|1";
    			oddsId = oddsId + "|" + "1|0|" +  pankou + "|0";
    		}else if(typedetail.contains("大")){
    			selectionId = selectionId + "|" + "3|0|" +  pankou + "|0";
    			oddsId = oddsId + "|" + "3|0|" +  pankou + "|1";
    		}else if(typedetail.contains("小")){
    			selectionId = selectionId + "|" + "4|0|" +  pankou + "|1";
    			oddsId = oddsId + "|" + "4|0|" +  pankou + "|1";
    		}
    		
    		
    		jb.put("selectionId", selectionId);
    		jb.put("oddsFormat", 4);
    		jb.put("oddsId", oddsId);
    		
    		
    		String currentTimestr = Long.toString(System.currentTimeMillis());
    		
    		String selectionData = "[" + jb.toString() + "]";
    		
    		
    		selectionData = URLEncoder.encode(selectionData, "UTF-8");
    		
    		System.out.println(df.format(System.currentTimeMillis()) + "updatePS38Ratio, request selectionId:" + selectionId);
    		
    		//https://www.ps3838.com/member-service/v1/multiTicket?selectionData=11&_=1535076813915&locale=zh_CN
    		
    		
    	//	String url = ADDRESS + "member-service/v1/multiTicket?selectionData=" + selectionData + "&_=" + currentTimestr + "local=zh_CN";
    		
    		
    		String url = ADDRESS + "member-service/v2/ticket?selectionId=" +  URLEncoder.encode(selectionId, "UTF-8") + "&ot=4&_"+ currentTimestr +"&locale=zh_CN";
    		
    		
    		
            HttpRequest request = HttpRequest
                    //.newBuilder(URI.create("http://hga020.com/"))
                    .newBuilder(URI.create(url))
                    //.header("Host", "www.ps3838.com")//携带的参数
                    
                    .header("Accept-Encoding", "")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("X-Requested-With", "XMLHttpRequest")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(20))//20秒过期
                    .GET()
                    .build();
    		
            
            res = getReponse(request);
            
            if(!res.contains("minStake") ) {
            	res = getReponse(request);
            }
            
            if(res.contains("minStake")) {
            	
            	
            	
            	
            	//JSONArray ja = new JSONArray(res);
            	JSONObject jb1 = new JSONObject(res);
            	
            	
            	Map<String, String> map=new HashMap<String, String>();
            	
            	if(jb1.getString("status").toLowerCase().equals("unavailable")) {
            		System.out.println("ps38 ticket status not ok:");
            		System.out.println(res);
            		return null;
            	}
            	
            	map.put("ratio", jb1.getString("odds"));
            	map.put("maxbet", Double.toString(jb1.getDouble("maxStake")));
            	map.put("minbet", Double.toString(jb1.getDouble("minStake")));
            	
            	String selectionIdStr = jb1.getString("selectionId");
            	String pankoustr = selectionIdStr.split("\\|")[7];
            	
            	//TODO: remove test code
            	//selectionIdStr = selectionIdStr.replace(betid, fakebetid);
            	
            	//selectionIdStr = selectionIdStr.replace("0.00", "1.00");
            	//end
            	
            	map.put("selectionId", selectionIdStr);
            	
            	System.out.println(df.format(System.currentTimeMillis()) + "updatePS38Ratio, response selectionId:" + res);
            	
            	
            	if(typedetail.contains("主")) {
            		pankoustr = Double.toString(0.0-Double.parseDouble(pankoustr));
        		}
            	

            	map.put("pankou", pankoustr);
            	
            	return map;
            }
            
            
            System.out.println(df.format(System.currentTimeMillis()) + "更新  PS38 Ratio失败" + res);
            
            if(res.contains("{\"error\":403}")) {
            	updateStatusCode(-1);
            }
            
            
            return null;
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    		
    		System.out.println("Exception 更新  PS38 Ratio失败" + res);
    		
    	}
    	
    	return null;
    	
    }
    
    
    
    
    
    
    public Map<String ,String> rebet(Map<String, String> oddUpdRes, int betgold) {
    	
    	Map<String ,String> resmap = new HashMap<String, String>();
    	
    	String betres = "";
    	
    	
    	long startbettime = System.currentTimeMillis();
    	
    	SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	
    	try {
    		
    		//Map<String, String> res = updatePS38Ratio(betid,eventid, bettype, typedetail, pankouarg);
    		
    		//bet-placement/buyV2?uniqueRequestId=e77bfc70-315f-9709-d5ba-e5febd28524e&locale=zh_CN
    		
    		String url = ADDRESS + "bet-placement/buyV2?uniqueRequestId=" + generateUUID() + "&locale=zh_CN";
    		
    		
    		
    		
    		
    		
    		
    		JSONArray ja = new JSONArray();
    		
    		JSONObject jb = new JSONObject();
    		
    		jb.put("stake", betgold);
    		jb.put("selectionId", oddUpdRes.get("selectionId"));
    		jb.put("stake", betgold);
    		jb.put("odds", oddUpdRes.get("ratio"));
    		jb.put("wagerType", "NORMAL");
    		jb.put("uniqueRequestId", generateUUID());

    		ja.put(jb);
    		
    		JSONObject jb1 = new JSONObject();
    		jb1.put("oddsFormat", 4);
    		jb1.put("selections", ja);
    		
    		

    		
    		
    		
    		
    		
    		
    		System.out.println(dfSec.format(System.currentTimeMillis()) + "ps38 dobet request str:" + jb1.toString());
    		
    		
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type","application/json")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(20))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString(jb1.toString()))
                    .build();
    		
            
            
    		
            betres = getReponse(request);
            
            System.out.println(dfSec.format(System.currentTimeMillis()) + "   ps38 dobet betres:" + betres);
            
            
            if(betres.contains("request timed out")) {
            	
            	Thread.sleep(2000);
            	
            	Map<String, String> checkres = requestTimeoutBetCheck(startbettime);
    			
    			if(checkres == null) {
            		Common.logOut("投注超时，注单状态暂时无法确认, 返回");
                	resmap.put("status", "-4");
                	return resmap;
    			}
    			
    			if(checkres.get("status").equals("0")||checkres.get("status").equals("1")) {
    				
    				Common.logOut("注单超时已确认，进单返回结果");
    				
    				checkres.put("eventId", oddUpdRes.get("selectionId").split("\\|")[2]);
    				return checkres;
    			}
            	
        		
            	
            	return checkres;
    		}
            
            
            
            
            if(betres.contains("ACCEPTED")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "1");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	//resmap.put("betgold", Double.toString(resjb.getDouble("risk")));
            	
            	return resmap;
            }else if(betres.contains("PENDING_ACCEPTANCE")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "0");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	return resmap;
            	
            }
            

    	}catch(Exception e) {
    		e.printStackTrace();
    		
    		
    		
        	
        	return resmap;
    		
    	}
    	
    	System.out.println(dfSec.format(System.currentTimeMillis()) + "   ps38补单失败:" + betres);

    	resmap.put("status", "-1");
    	
    	return resmap;
    	
    }
    
    
    
    
    public void getBalance() {
    	try {
    		
    		HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(ADDRESS + "member-service/v2/account-balance?locale=zh_CN"))
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Referer", "https://www.ps3838.com/zh-cn/")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(10))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString("json"))
                    .build();


            
            
            
            String res = getReponse(request);
            
            
//            SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//            
//            System.out.println(df.format(System.currentTimeMillis()) + "   ps38 bet balance result:" + res);
            
            
            if(res.contains("betCredit")) {  	
            	JSONObject details = new JSONObject(res);


            	double balance = details.getDouble("betCredit");
            	
            	NegativeRatioClient.mainWnd.updatePS38AccountBalance(ACCOUNT, Double.toString(balance));
            	
            	updateStatusCode(2);
            }else {
            	
            	if(res.contains("request timed out")) {
            		
            		System.out.println("request time out, no need to relogin");
            		
            	
            	}else {
            		
            		System.out.println("ps38 get balance failed:" + res);
            		
            		updateStatusCode(-1);
            	}
            	
            	
            	
            	
            	
            }
    		
    	}catch(Exception e) {
    		
    		System.out.println("ps38 get balance failed exception:");
    		
    		updateStatusCode(-1);
    		e.printStackTrace();
    	}
    }


	
    
    public String generateUUID() {
    	return a() + a() + "-" + a() + "-" + a() + "-" + a() + "-" + a() + a() + a();
    }

    
    public String a() {
    	
    	Double.toString(Math.floor((1 + Math.random()) * 65536));
    	
    	Math.floor((1 + Math.random()) * 65536);
    	
    	Math.random();
    	
    	
    	return Integer.toHexString((int)(Math.floor((1 + Math.random()) * 65536))).substring(1);
    	
    	
    }


	public void updateps38BetLogData(Vector<BetAdyData> betLogDatas) {
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
    	try {

    		
    	

    		HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(ADDRESS + "member-service/v2/my-bets?_=1542380052153&locale=zh_CN"))
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(10))//2秒过期
                    .GET()
                    .build();


            
            String res = getReponse(request);
            
            
            //SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss");// 设置日期格式
            
            
            if(null != res && res.contains("[")) {

            	JSONArray bets = new JSONArray(res); 
            	

            	
            	
            	for(BetAdyData bd: betLogDatas) {
            	
            		if(bd.ps38betres.equals("0")) {
            			
            			for(int i = 0; i < bets.length(); i++ ) {
            				
            				JSONArray bet = bets.getJSONArray(i);
            				
            				
            				
            				
            				if(Long.toString(bet.getLong(0)).equals(bd.wagerId) &&  bet.getString(11).equals("OPEN")) {
            					
            					
            					System.out.println(df.format(System.currentTimeMillis()) + "   ps38比赛确认:" + bd.teams);
            					
            					System.out.println(bet.getLong(0));
                				System.out.println(bet.getString(11));
            					
            					bd.ps38betres = "2";
            					
            					int betAdyGold = NegativeRatioClient.betCtrMng.checkBetGold(null, "", bd.gid);
            					
            					NegativeRatioClient.betCtrMng.updateBetLog(bd.gid, "106", Integer.toString(betAdyGold));
            					
            					break;
            				}else if(Long.toString(bet.getLong(0)).equals(bd.wagerId)){
            					System.out.println(df.format(System.currentTimeMillis()) + "   ps38比赛状态未确认:" + bd.teams+ "  " + bet.getString(11));
            					
            					System.out.println(bet.getLong(0));
                				System.out.println(bet.getString(11));
                				
                				System.out.println("未确认string:" + bet.toString());
                				
                				if(bet.getString(11).equals("CANCELLED")) {
                					bd.ps38betres = "-3";
                					NegativeRatioClient.betCtrMng.updateBetLog(bd.gid, "107", "");
                				}
                				
                				//
                				
                				break;
            				}
            				
            			}
            			

            		}
            	}
            	
            }
    		
    	}catch(Exception e) {
    		
    		System.out.println(df.format(System.currentTimeMillis()) + "  ps38比赛状态未确认:");

    		e.printStackTrace();
    	}
		
	}
	
	
    public String getMybetsUrl()
    {
   	 	return ADDRESS + "zh-cn/account/my-bets-full";
    }
    
    
    public String getAccUrl() {
    	return ADDRESS + "zh-cn/account/statements";
    }
    
    public void setCookie() {
   	 List<HttpCookie> cookies = cookieManager.getCookieStore().getCookies();
   	 for(HttpCookie c:cookies)
		 {
   		 
   		 String cookiestr = c.toString();
   		 System.out.println(cookiestr);
   		 
   		 Browser.setCookie(c.toString(), "https://www.ps3838.com/");
		 }
	}
    
    
    
    private void parseMatches(String matchStr, String eventidarg) {
    	
    	try {
    		
    		ps38Events.clear();
    		
    		
    		JSONObject sports = new JSONObject(matchStr);
    		
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
    		
    		
    		//滚球盘
    		JSONArray rollGame = sports.getJSONArray("l");
    		JSONArray rollEvents = rollGame.getJSONArray(0);
    		rollEvents = rollEvents.getJSONArray(2);
    		
    		
    		
    		JSONArray oneLeague = null;
    		
    		for(int i = 0; i < rollEvents.length(); i++){
    			oneLeague = rollEvents.getJSONArray(i);
    			
    			String leagueName = oneLeague.getString(1);
    			
    			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
    				continue;
    			}
    			
    			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
    			
    			
    			JSONArray oneEvent = null;
    			for(int j = 0; j < oneLeagueEvents.length(); j++) {
    				oneEvent = oneLeagueEvents.getJSONArray(j);
    				
    				long eventId = oneEvent.getLong(0);
    				
    				
    				if(!eventidarg.equals(Long.toString(eventId))) {
    					continue;
    				}
    				
    				String homeTeam = oneEvent.getString(1);
    				String awayTeam = oneEvent.getString(2);
    				long eventTime = oneEvent.getLong(4);
    				
    				
    				
    				
    				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
        				continue;
        			}
    				
    				
    				
    				
    				JSONObject odds = oneEvent.getJSONObject(8);
    				
    				int homeTeamScore = 0;
    				int awayTeamScore = 0;
    				

    				try {
    					
        				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
        				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
    					
    					
    				}catch(Exception e) {
    					//e.printStackTrace();
    				}
    				
    				String duringTime = "";
    				
    				try {
    					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
    				}catch(Exception e) {
    					
    				}
    				
    				
    				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
    				
    				
    				//Event ps38event = new Event();
    				
    				for(Event e: ps38event) {
        				e.eventId = eventId;
        				e.leagueName = leagueName;
        				e.homeTeam = homeTeam;
        				e.awayTeam = awayTeam;
        				e.eventTime = eventTime;
        				e.duringTime = duringTime;
        				e.homeTeamScore = homeTeamScore;
        				e.awayTeamScore = awayTeamScore;
    				}
    				

    				
    				boolean[] hasPankou = {false, false,false,false,false};
    				
//    				System.out.println(leagueName);
//    				
//    				System.out.println(eventId);
//    				System.out.println(homeTeam);
//    				System.out.println(awayTeam);
//    				System.out.println(df.format(eventTime));
//    				
//    				System.out.println(Integer.toString(homeTeamScore)+ ":" + Integer.toString(awayTeamScore));
//    				
//    				System.out.println(duringTime);
    				
    				
    				
    				
    				int len = odds.length();
    				
    				
    				if(len >=1 ) {
        				//全场
        				JSONArray whole = odds.getJSONArray("0");
        				
        				
        				
        				//全场让球盘盘口赔率
        				JSONArray wholeRQP = whole.getJSONArray(0);    	
        				
        				//System.out.println("wholeRQP:" + wholeRQP.toString());
        				
        				
        				
        				
        				for(int ii = 0; ii < wholeRQP.length(); ii++) {
        					
            				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
            				
            				
            				//System.out.println("wholeRQPDetail:" + wholeRQPDetail.toString());
            				
//            				Double wholeRQPPankou = wholeRQPDetail.getDouble(2);
//            				Double wholeRQPPankouUp = wholeRQPDetail.getDouble(3);
//            				Double wholeRQPPankouDown = wholeRQPDetail.getDouble(4);
            				
            				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
            				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
            				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
            				
            				
            				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
            				
            				
            				
            				
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
            				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
            				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
            				ps38event[ii].wholeRQPBetID = wholeRQPBetID;
            				
//            				System.out.println(wholeRQPPankou);
//            				System.out.println(wholeRQPPankouUp);
//            				System.out.println(wholeRQPPankouDown);
        					
        				}
        				
        				

        				
        				
        				
        				//全场大小球盘盘口赔率
        				JSONArray wholeDXP = whole.getJSONArray(1);
        				
        				for(int ii = 0; ii < wholeDXP.length(); ii++) {
            				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
            				
            				
            				
            				
            				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
            				Double wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
            				Double wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
            				
            				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
            				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
            				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
            				ps38event[ii].wholeDXPBetID = wholeDXPBetID;


        				}
        				

        				
    				}
    				



    				
    				for(int ii = 0; ii < hasPankou.length; ii++) {
    					if(hasPankou[ii] == true) {
        					ps38Events.add(ps38event[ii]);
        				}
    				}
    				

    			}
    			
    		}
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		
    		//单式盘
    		JSONArray danshiGame = sports.getJSONArray("n");
    		JSONArray danshiEvents = danshiGame.getJSONArray(0);
    		danshiEvents = danshiEvents.getJSONArray(2);
    		
    		
    		
    		//JSONArray oneLeague = null;
    		
    		for(int i = 0; i < danshiEvents.length(); i++){
    			oneLeague = danshiEvents.getJSONArray(i);
    			
    			String leagueName = oneLeague.getString(1);
    			
    			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
    				continue;
    			}
    			
    			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
    			
    			
    			JSONArray oneEvent = null;
    			for(int j = 0; j < oneLeagueEvents.length(); j++) {
    				oneEvent = oneLeagueEvents.getJSONArray(j);
    				
    				
    				
    				long eventId = oneEvent.getLong(0);
    				
    				if(!eventidarg.equals(Long.toString(eventId))) {
    					continue;
    				}
    				
    				String homeTeam = oneEvent.getString(1);
    				String awayTeam = oneEvent.getString(2);
    				long eventTime = oneEvent.getLong(4);
    				
    				JSONObject odds = oneEvent.getJSONObject(8);
    				
    				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
        				continue;
        			}
    				
    				
    				int homeTeamScore = 0;
    				int awayTeamScore = 0;
    				

    				try {
    					
        				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
        				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
    					
    					
    				}catch(Exception e) {
    					//e.printStackTrace();
    				}
    				
    				String duringTime = "";
    				
    				try {
    					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
    				}catch(Exception e) {
    					
    				}
    				
    				
    				
    				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
    				
    				
    				//Event ps38event = new Event();
    				
    				for(Event e: ps38event) {
        				e.eventId = eventId;
        				e.leagueName = leagueName;
        				e.homeTeam = homeTeam;
        				e.awayTeam = awayTeam;
        				e.eventTime = eventTime;
        				e.duringTime = duringTime;
        				e.homeTeamScore = homeTeamScore;
        				e.awayTeamScore = awayTeamScore;
    				}
    				

    				
    				boolean[] hasPankou = {false, false,false, false,false};
    				
//    				System.out.println(leagueName);
//    				
//    				System.out.println(eventId);
//    				System.out.println(homeTeam);
//    				System.out.println(awayTeam);
//    				System.out.println(df.format(eventTime));
//    				
//    				System.out.println(Integer.toString(homeTeamScore)+ ":" + Integer.toString(awayTeamScore));
//    				
//    				System.out.println(duringTime);
    				
    				
    				
    				
    				int len = odds.length();
    				
    				
    				if(len >=1 ) {
        				//全场
    					
    					//System.out.println("odds~~~~~~~~~~~" + odds.toString());
    					
        				JSONArray whole = odds.getJSONArray("0");
        				
        				
        				
        				//全场让球盘盘口赔率
        				JSONArray wholeRQP = whole.getJSONArray(0);    	
        				
        				//System.out.println("wholeRQP:" + wholeRQP.toString());
        				
        				
        				
        				
        				//if(wholeRQP.length() >0) {
        				for(int ii = 0; ii < wholeRQP.length(); ii++) {
        					
        				
        					
            				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
            				

            				
            				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
            				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
            				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
            				
            				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
            				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
            				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
            				ps38event[ii].wholeRQPBetID = wholeRQPBetID;

        					
        				}
        				
        				

        				
        				
        				
        				//全场大小球盘盘口赔率
        				JSONArray wholeDXP = whole.getJSONArray(1);

        				for(int ii = 0; ii< wholeDXP.length(); ii++) {
            				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
            				
            				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
            				Double wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
            				Double wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
            				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
            				
            				
            				hasPankou[ii] = true;
            				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
            				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
            				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
            				ps38event[ii].wholeDXPBetID = wholeDXPBetID;

        				}
        				

        				
    				}
    				

    				

    				for(int ii = 0; ii < hasPankou.length; ii++) {
    					if(hasPankou[ii] == true) {
        					ps38Events.add(ps38event[ii]);
        				}
    				}
    				
    				
    				

    			}
    			
    		}
    		
    		
    		
    		
    		
    		
    		
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    		
    	}
    	
    	
    }
    
    
    public String updateMatches(String eventid) {
    	
    	
    	try {
    		
    		
        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	String oduri = ADDRESS + "sports-service/sv/odds/events?mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis) + "&l=3&v=0&me=0&more=false&c=CN&tm=0&g=&pa=0&_=" + currentTimeMillis + "&locale=zh_CN";
        	
        	
        	//														mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=2018-11-22&l=3&v=0&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=1542785438602&locale=zh_CN
        	
        	//https://www.ps3838.com/ sports-service/sv/odds/events?mk=1&sp=29&ot=1&btg=1&o=1&lg=&ev=&d=2018-11-22&l=3&v=1542785561407&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=1542785438522&locale=zh_CN
        	
        	
        	//https://www.ps3838.com/sports-service/sv/odds/events?mk=2&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=2018-11-21                          &l=3&v=1542709885876&more=false&c=CN&tm=0&g=QQ%3D%3D&pa=0&_=1542709206136&locale=zh_CN

        	
            HttpRequest request = HttpRequest
                    //.newBuilder(URI.create("http://hga020.com/"))
                    .newBuilder(URI.create(oduri))
                    //.header("Host", "www.ps3838.com")//携带的参数
                    
                    .header("Accept-Encoding", "")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("X-Requested-With", "XMLHttpRequest")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(20))//2秒过期
                    .GET()
                    .build();
            
            
            
            if(hasLang == false) {
                HttpCookie cookie1 = new HttpCookie("skin", "ps3838");
                cookie1.setDomain(".ps3838.com");
                cookie1.setPath("/");
                cookie1.setVersion(0);
                
                HttpCookie cookie2 = new HttpCookie("lang", "zh_CN");
                cookie2.setDomain(".ps3838.com");
                cookie2.setPath("/");
                cookie2.setVersion(0);
                
                cookieManager.getCookieStore().add(null, cookie1);
                cookieManager.getCookieStore().add(null, cookie2);
                
                hasLang = true;
            }
            
            
            String res = getReponse(request);
            
            if(res.equals("")) {
            	res = getReponse(request);
            }

            if(res.toLowerCase().contains("name=\"robots\"")) {
            	updateStatusCode(0);
            	return res;
            }
            
            
            if(!res.contains("{")) {
            	
            	Common.logOut("失败updatematches:" + res);
            	
            	return "";
            }
            
            parseMatches(res, eventid);
            
            return res;
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	
    	return "";
    	
    }


	public Map<String, String> manualRebetUpdatePS38Ratio(String betid, String eventid, String bettype,
			String typedetail, String pankouarg) {
    	String res = "";

    	try {
    		
    		//selectionData: [{"selectionId":"556778348|885420736|0|2|0|0|-0.25|0","oddsFormat":1,"oddsId":"885420736|0|2|0|0|-0.25|0"}]
    		
    		//selectionId : "betid|eventid|whole(0)/half(1)|R(2)O(3)|主客场(0,1)/大小球(3,4)|0|pankou|主客(0)/大小(1)"
    		//oddsFormat : 2
    		//oddsId: eventid|whole(0)/half(1)|R(2)O(3)|主客场(0,1)/大小球(3,4)|0|pankou|主客(0)/大小(1)
    		
    		
    		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    		
    		
    		String pankou = pankouarg;
    		
    		if(typedetail.contains("主")) {
    			pankou = Double.toString(0.0-Double.parseDouble(pankouarg));
    		}
    		
    		
    		
    		
    		
//    		boolean isWhole = false;
//    		
//    		if(bettype.contains("全场")) {
//    			isWhole = true;
//    		}
//    		
//    		
//    		betid = getBetidByEventid(eventid, isWhole);
    		
    		if(betid.equals("")) {
    			return null; 
    		}
    		
    		JSONObject jb = new JSONObject();
    		
    		
    		String fakebetid = Long.toString(Long.parseLong(betid) + 1);
    		
    		
    		String selectionId = betid + "|" + eventid;
    		String oddsId = eventid;
    		
    		if(bettype.contains("全场")) {
    			selectionId = selectionId + "|" + "0";
    			oddsId = oddsId + "|" + "0";
    		}else {
    			selectionId = selectionId + "|" + "1";
    			oddsId = oddsId + "|" + "1";
    		}
    		
    		if(bettype.contains("让球")) {
    			selectionId = selectionId + "|" + "2";
    			oddsId = oddsId + "|" + "2";
    		}else {
    			selectionId = selectionId + "|" + "3";
    			oddsId = oddsId + "|" + "3";
    		}
    		
    		if(typedetail.contains("主")) {
    			selectionId = selectionId + "|" + "0|0|" +  pankou + "|0";
    			oddsId = oddsId + "|" + "0|0|" +  pankou + "|0";
    		}else if(typedetail.contains("客")){
    			selectionId = selectionId + "|" + "1|0|" +  pankou + "|1";
    			oddsId = oddsId + "|" + "1|0|" +  pankou + "|0";
    		}else if(typedetail.contains("大")){
    			selectionId = selectionId + "|" + "3|0|" +  pankou + "|0";
    			oddsId = oddsId + "|" + "3|0|" +  pankou + "|1";
    		}else if(typedetail.contains("小")){
    			selectionId = selectionId + "|" + "4|0|" +  pankou + "|1";
    			oddsId = oddsId + "|" + "4|0|" +  pankou + "|1";
    		}
    		
    		
    		jb.put("selectionId", selectionId);
    		jb.put("oddsFormat", 4);
    		jb.put("oddsId", oddsId);
    		
    		
    		String currentTimestr = Long.toString(System.currentTimeMillis());
    		
    		String selectionData = "[" + jb.toString() + "]";
    		
    		
    		selectionData = URLEncoder.encode(selectionData, "UTF-8");
    		
    		System.out.println(df.format(System.currentTimeMillis()) + "manualRebetUpdatePS38Ratio, request selectionId:" + selectionId);
    		
    		//https://www.ps3838.com/member-service/v1/multiTicket?selectionData=11&_=1535076813915&locale=zh_CN
    		
    		
    	//	String url = ADDRESS + "member-service/v1/multiTicket?selectionData=" + selectionData + "&_=" + currentTimestr + "local=zh_CN";
    		
    		
    		String url = ADDRESS + "member-service/v2/ticket?selectionId=" +  URLEncoder.encode(selectionId, "UTF-8") + "&ot=4&_"+ currentTimestr +"&locale=zh_CN";
    		
    		
    		
            HttpRequest request = HttpRequest
                    //.newBuilder(URI.create("http://hga020.com/"))
                    .newBuilder(URI.create(url))
                    //.header("Host", "www.ps3838.com")//携带的参数
                    
                    .header("Accept-Encoding", "")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("X-Requested-With", "XMLHttpRequest")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(20))//20秒过期
                    .GET()
                    .build();
    		
            
            res = getReponse(request);
            
            if(!res.contains("minStake") ) {
            	res = getReponse(request);
            }
            
            if(res.contains("minStake")) {
            	
            	
            	
            	
            	//JSONArray ja = new JSONArray(res);
            	JSONObject jb1 = new JSONObject(res);
            	
            	
            	Map<String, String> map=new HashMap<String, String>();
            	
            	if(jb1.getString("status").toLowerCase().equals("unavailable")) {
            		System.out.println("ps38 ticket status not ok:");
            		System.out.println(res);
            		return null;
            	}
            	
            	map.put("ratio", jb1.getString("odds"));
            	map.put("maxbet", Double.toString(jb1.getDouble("maxStake")));
            	map.put("minbet", Double.toString(jb1.getDouble("minStake")));
            	
            	String selectionIdStr = jb1.getString("selectionId");
            	String pankoustr = selectionIdStr.split("\\|")[7];
            	
            	
            	
            	map.put("selectionId", selectionIdStr);
            	
            	System.out.println(df.format(System.currentTimeMillis()) + "manualRebetUpdatePS38Ratio, response selectionId:" + res);
            	
            	
            	if(typedetail.contains("主")) {
            		pankoustr = Double.toString(0.0-Double.parseDouble(pankoustr));
        		}
            	

            	map.put("pankou", pankoustr);
            	
            	return map;
            }
            
            
            System.out.println(df.format(System.currentTimeMillis()) + "manualRebetUpdatePS38Ratio  更新  PS38 Ratio失败" + res);
            
            
            
            
            return null;
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    		
    		System.out.println("manualRebetUpdatePS38Ratio Exception 更新  PS38 Ratio失败" + res);
    		
    	}
    	
    	return null;
	}
	
	
	
	
	
	
	
	
    public Map<String ,String> manualDobet(Map<String, String> oddUpdRes, int betgold) {
    	
    	Map<String ,String> resmap = new HashMap<String, String>();
    	
    	String betres = "";
    	
    	SimpleDateFormat dfSec = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    	
    	try {
    		
    		//Map<String, String> res = updatePS38Ratio(betid,eventid, bettype, typedetail, pankouarg);
    		
    		//bet-placement/buyV2?uniqueRequestId=e77bfc70-315f-9709-d5ba-e5febd28524e&locale=zh_CN
    		
    		String url = ADDRESS + "bet-placement/buyV2?uniqueRequestId=" + generateUUID() + "&locale=zh_CN";
    		
    		
    		
    		
    		
    		
    		
    		JSONArray ja = new JSONArray();
    		
    		JSONObject jb = new JSONObject();
    		
    		jb.put("stake", betgold);
    		jb.put("selectionId", oddUpdRes.get("selectionId"));
    		jb.put("stake", betgold);
    		jb.put("odds", oddUpdRes.get("ratio"));
    		jb.put("wagerType", "NORMAL");
    		jb.put("uniqueRequestId", generateUUID());

    		ja.put(jb);
    		
    		JSONObject jb1 = new JSONObject();
    		jb1.put("oddsFormat", 4);
    		jb1.put("selections", ja);
    		
    		

    		
    		
    		
    		
    		
    		
    		System.out.println(dfSec.format(System.currentTimeMillis()) + "ps38 dobet request str:" + jb1.toString());
    		
    		
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .header("Content-Type","application/json")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(30))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString(jb1.toString()))
                    .build();
    		
            
            
    		
            betres = getReponse(request);
            
            System.out.println(dfSec.format(System.currentTimeMillis()) + "   ps38 dobet betres:" + betres);
            
            
            //TODO: 检查投注进单以及待确认注单， 看有没有办法检查出具体状态
    		if(betres.contains("request timed out")) {
        		Common.logOut("注单状态暂时无法确认");
            	resmap.put("status", "-4");
    		}
            
            
            
            
            if(betres.contains("ACCEPTED")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "1");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	//resmap.put("betgold", Double.toString(resjb.getDouble("risk")));
            	
            	return resmap;
            }else if(betres.contains("PENDING_ACCEPTANCE")) {
            	
            	JSONObject resjb = new JSONObject(betres);
            	JSONArray resja = resjb.getJSONArray("response");
            	
            	resjb = resja.getJSONObject(0);
            	
            	resmap.put("wagerId", Long.toString(resjb.getLong("wagerId")));
            	resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	resmap.put("ratio", Double.toString(resjb.getDouble("odds")));
            	
            	resmap.put("status", "0");
            	
            	String timel = dfSec.format(System.currentTimeMillis());
            	
            	resmap.put("bettime", timel);
            	
            	return resmap;
            	
            }
            
    	}catch(Exception e) {
    		
    		
    		e.printStackTrace();
    		
    		
    		
        	
        	return resmap;
    		
    		
    	}
    	
    	
    	
    	
    	System.out.println(dfSec.format(System.currentTimeMillis()) + "   ps38投注失败:" + betres);

    	resmap.put("status", "-1");
    	
    	return resmap;
    	
    }
	
	
	
	
	public Event grabOneEvent(String eventidarg, String pankou, String typedetail) {
		
    	try {
    		
    		Vector<Event> ps38eventstmp = new Vector<Event>();
    		
    		
        	SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
        	
        	long currentTimeMillis = System.currentTimeMillis();
        	
        	String oduri = ADDRESS + "sports-service/sv/odds/events?mk=1&sp=29&ot=4&btg=1&o=1&lg=&ev=&d=" + df.format(currentTimeMillis) + "&l=3&v=0&me=0&more=false&c=CN&tm=0&g=&pa=0&_=" + currentTimeMillis + "&locale=zh_CN";
        	
            HttpRequest request = HttpRequest
                    //.newBuilder(URI.create("http://hga020.com/"))
                    .newBuilder(URI.create(oduri))
                    //.header("Host", "www.ps3838.com")//携带的参数
                    
                    .header("Accept-Encoding", "")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "application/json, text/javascript, */*; q=0.01")
                    .header("X-Requested-With", "XMLHttpRequest")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(20))//2秒过期
                    .GET()
                    .build();
            
            
            
            if(hasLang == false) {
                HttpCookie cookie1 = new HttpCookie("skin", "ps3838");
                cookie1.setDomain(".ps3838.com");
                cookie1.setPath("/");
                cookie1.setVersion(0);
                
                HttpCookie cookie2 = new HttpCookie("lang", "zh_CN");
                cookie2.setDomain(".ps3838.com");
                cookie2.setPath("/");
                cookie2.setVersion(0);
                
                cookieManager.getCookieStore().add(null, cookie1);
                cookieManager.getCookieStore().add(null, cookie2);
                
                hasLang = true;
            }
            
            
            String res = getReponse(request);
            
            if(res.equals("")) {
            	res = getReponse(request);
            }

            if(res.toLowerCase().contains("name=\"robots\"")) {
            	updateStatusCode(0);
            	return null;
            }
            
            
            if(res.contains("{")) {
            	

            		
            		JSONObject sports = new JSONObject(res);
            		
            		
            		//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:MM:SS");
            		
            		
            		//滚球盘
            		JSONArray rollGame = sports.getJSONArray("l");
            		JSONArray rollEvents = rollGame.getJSONArray(0);
            		rollEvents = rollEvents.getJSONArray(2);
            		
            		
            		
            		JSONArray oneLeague = null;
            		
            		for(int i = 0; i < rollEvents.length(); i++){
            			oneLeague = rollEvents.getJSONArray(i);
            			
            			String leagueName = oneLeague.getString(1);
            			
            			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
            				continue;
            			}
            			
            			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
            			
            			
            			JSONArray oneEvent = null;
            			for(int j = 0; j < oneLeagueEvents.length(); j++) {
            				oneEvent = oneLeagueEvents.getJSONArray(j);
            				
            				long eventId = oneEvent.getLong(0);
            				
            				
            				if(!eventidarg.equals(Long.toString(eventId))) {
            					continue;
            				}
            				
            				String homeTeam = oneEvent.getString(1);
            				String awayTeam = oneEvent.getString(2);
            				long eventTime = oneEvent.getLong(4);
            				
            				
            				
            				
            				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
                				continue;
                			}
            				
            				
            				
            				
            				JSONObject odds = oneEvent.getJSONObject(8);
            				
            				int homeTeamScore = 0;
            				int awayTeamScore = 0;
            				

            				try {
            					
                				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
                				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
            					
            					
            				}catch(Exception e) {
            					//e.printStackTrace();
            				}
            				
            				String duringTime = "";
            				
            				try {
            					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
            				}catch(Exception e) {
            					
            				}
            				
            				
            				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
            				
            				
            				//Event ps38event = new Event();
            				
            				for(Event e: ps38event) {
                				e.eventId = eventId;
                				e.leagueName = leagueName;
                				e.homeTeam = homeTeam;
                				e.awayTeam = awayTeam;
                				e.eventTime = eventTime;
                				e.duringTime = duringTime;
                				e.homeTeamScore = homeTeamScore;
                				e.awayTeamScore = awayTeamScore;
            				}
            				

            				
            				boolean[] hasPankou = {false, false,false,false,false};
		
            				int len = odds.length();
            				
            				
            				if(len >=1 ) {
                				//全场
                				JSONArray whole = odds.getJSONArray("0");
                				
                				
                				
                				//全场让球盘盘口赔率
                				JSONArray wholeRQP = whole.getJSONArray(0);    	
                				
                				//System.out.println("wholeRQP:" + wholeRQP.toString());
                				
                				
                				
                				
                				for(int ii = 0; ii < wholeRQP.length(); ii++) {
                					
                    				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
  
                    				
                    				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
                    				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
                    				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
                    				
                    				
                    				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
                    				
                    				
                    				
                    				
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
                    				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
                    				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
                    				ps38event[ii].wholeRQPBetID = wholeRQPBetID;
                    				

                					
                				}
                				
                				

                				
                				
                				
                				//全场大小球盘盘口赔率
                				JSONArray wholeDXP = whole.getJSONArray(1);
                				
                				for(int ii = 0; ii < wholeDXP.length(); ii++) {
                    				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
                    				
                    				
                    				
                    				
                    				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
                    				Double wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
                    				Double wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
                    				
                    				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
                    				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
                    				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
                    				ps38event[ii].wholeDXPBetID = wholeDXPBetID;


                				}
                				

                				
            				}
            				



            				
            				for(int ii = 0; ii < hasPankou.length; ii++) {
            					if(hasPankou[ii] == true) {
            						ps38eventstmp.add(ps38event[ii]);
                				}
            				}
            				

            			}
            			
            		}
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		
            		//单式盘
            		JSONArray danshiGame = sports.getJSONArray("n");
            		JSONArray danshiEvents = danshiGame.getJSONArray(0);
            		danshiEvents = danshiEvents.getJSONArray(2);
            		
            		
            		
            		//JSONArray oneLeague = null;
            		
            		for(int i = 0; i < danshiEvents.length(); i++){
            			oneLeague = danshiEvents.getJSONArray(i);
            			
            			String leagueName = oneLeague.getString(1);
            			
            			if(leagueName.contains("角球") || leagueName.contains("红黄牌") || leagueName.contains("晋级")) {
            				continue;
            			}
            			
            			JSONArray oneLeagueEvents = oneLeague.getJSONArray(2);
            			
            			
            			JSONArray oneEvent = null;
            			for(int j = 0; j < oneLeagueEvents.length(); j++) {
            				oneEvent = oneLeagueEvents.getJSONArray(j);
            				
            				
            				
            				long eventId = oneEvent.getLong(0);
            				
            				if(!eventidarg.equals(Long.toString(eventId))) {
            					continue;
            				}
            				
            				String homeTeam = oneEvent.getString(1);
            				String awayTeam = oneEvent.getString(2);
            				long eventTime = oneEvent.getLong(4);
            				
            				JSONObject odds = oneEvent.getJSONObject(8);
            				
            				if(homeTeam.contains("角球") || homeTeam.contains("红黄牌") || homeTeam.contains("晋级")) {
                				continue;
                			}
            				
            				
            				int homeTeamScore = 0;
            				int awayTeamScore = 0;
            				

            				try {
            					
                				homeTeamScore = oneEvent.getJSONArray(9).getInt(0);
                				awayTeamScore = oneEvent.getJSONArray(9).getInt(1);
            					
            					
            				}catch(Exception e) {
            					//e.printStackTrace();
            				}
            				
            				String duringTime = "";
            				
            				try {
            					duringTime = oneEvent.getString(16) + oneEvent.getString(15);
            				}catch(Exception e) {
            					
            				}
            				
            				
            				
            				Event[] ps38event = {new Event(), new Event(), new Event(), new Event(), new Event()};
            				
            				
            				//Event ps38event = new Event();
            				
            				for(Event e: ps38event) {
                				e.eventId = eventId;
                				e.leagueName = leagueName;
                				e.homeTeam = homeTeam;
                				e.awayTeam = awayTeam;
                				e.eventTime = eventTime;
                				e.duringTime = duringTime;
                				e.homeTeamScore = homeTeamScore;
                				e.awayTeamScore = awayTeamScore;
            				}
            				

            				
            				boolean[] hasPankou = {false, false,false, false,false};
            				

            				
            				
            				int len = odds.length();
            				
            				
            				if(len >=1 ) {
                				//全场
            					
            					//System.out.println("odds~~~~~~~~~~~" + odds.toString());
            					
                				JSONArray whole = odds.getJSONArray("0");
                				
                				
                				
                				//全场让球盘盘口赔率
                				JSONArray wholeRQP = whole.getJSONArray(0);    	
                				
                				//System.out.println("wholeRQP:" + wholeRQP.toString());
                				
                				
                				
                				
                				//if(wholeRQP.length() >0) {
                				for(int ii = 0; ii < wholeRQP.length(); ii++) {
                					
                				
                					
                    				JSONArray wholeRQPDetail = wholeRQP.getJSONArray(ii);
                    				

                    				
                    				Double wholeRQPPankou = wholeRQPDetail.getDouble(0);
                    				String wholeRQPPankouUp = wholeRQPDetail.getString(3);
                    				String wholeRQPPankouDown = wholeRQPDetail.getString(4);
                    				
                    				String wholeRQPBetID = Long.toString(wholeRQPDetail.getLong(7));
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].wholerqppankou = Double.toString(wholeRQPPankou);
                    				ps38event[ii].wholeRQPPankouUp = wholeRQPPankouUp;
                    				ps38event[ii].wholeRQPPankouDown = wholeRQPPankouDown;
                    				ps38event[ii].wholeRQPBetID = wholeRQPBetID;

                					
                				}
                				
                				

                				
                				
                				
                				//全场大小球盘盘口赔率
                				JSONArray wholeDXP = whole.getJSONArray(1);

                				for(int ii = 0; ii< wholeDXP.length(); ii++) {
                    				JSONArray wholeDXPDetail = wholeDXP.getJSONArray(ii);
                    				
                    				Double wholeDXPPankou = wholeDXPDetail.getDouble(1);
                    				Double wholeDXPPankouUp = wholeDXPDetail.getDouble(2);
                    				Double wholeDXPPankouDown = wholeDXPDetail.getDouble(3);
                    				String wholeDXPBetID = Long.toString(wholeDXPDetail.getLong(4));
                    				
                    				
                    				hasPankou[ii] = true;
                    				ps38event[ii].wholeDXPPankou = Double.toString(wholeDXPPankou);
                    				ps38event[ii].wholeDXPPankouUp = Double.toString(wholeDXPPankouUp);
                    				ps38event[ii].wholeDXPPankouDown = Double.toString(wholeDXPPankouDown);
                    				ps38event[ii].wholeDXPBetID = wholeDXPBetID;

                				}
                				

                				
            				}
            				

            				

            				for(int ii = 0; ii < hasPankou.length; ii++) {
            					if(hasPankou[ii] == true) {
            						ps38eventstmp.add(ps38event[ii]);
                				}
            				}
            				
            				
            				

            			}
            			
            		}
            		
            		
            		
            		
            		
//                    String betpankoustr = "";
//                    
//                    if(typedetail.contains("主")) {
//                    	betpankoustr = Double.toString(0.0-Double.parseDouble(pankou));                    	
//            		}else {
//            			betpankoustr = pankou;
//            		}
                    
                    String betid = "";
                    
                    
                    for(int i = 0; i < ps38eventstmp.size(); i++) {
                    	Common.logOut(ps38eventstmp.elementAt(i).toString());
                    	
                    	Event event = ps38eventstmp.elementAt(i);
                    	
                    	if(typedetail.contains("主")||typedetail.contains("客")) {
                    		if(Math.abs(Double.parseDouble(pankou) - Double.parseDouble(event.wholerqppankou)) < 0.01) {
                    			betid = event.wholeRQPBetID;
                    			return event;
                    		}
                    	}else if(typedetail.contains("大")||typedetail.contains("小")) {
                    		if(Math.abs(Double.parseDouble(pankou) - Double.parseDouble(event.wholeDXPPankou)) < 0.01) {
                    			betid = event.wholeDXPBetID;
                    			return event;
                    			
                    		}
                    	}
                    	
                    }

                    return null;

            }else {
            	
            	Common.logOut("失败grabeventbyeventid:" + res);
            	
            	return null;
            }
            
            
            
           
    		
    	}catch(Exception e) {
    		e.printStackTrace();
    	}
    	
    	
    	return null;
		
	}
	
	
	
	
	public Map<String, String> requestTimeoutBetCheck(long time) {
		
		
		Common.logOut("Enter requestTimeoutBetCheck");
		
		SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		
		Map<String ,String> resmap = new HashMap<String, String>();
		
    	try {

    		HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(ADDRESS + "member-service/v2/my-bets?_=1542380052153&locale=zh_CN"))
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Referer", "https://www.ps3838.com/zh-cn/sports")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(10))//2秒过期
                    .GET()
                    .build();


            
            String res = getReponse(request);
            
            if(res.equals("")) {
            	
            	Thread.sleep(2000);
            	
            	res =  getReponse(request);
            }
            
            
            //SimpleDateFormat df = new SimpleDateFormat("MM-dd HH:mm:ss");// 设置日期格式
            
            
            if(null != res && res.contains("[")) {
            	
            	Common.logOut("requestTimeoutBetCheck res" + res);

            	JSONArray bets = new JSONArray(res); 
		
            			for(int i = 0; i < bets.length(); i++ ) {
            				
            				JSONArray bet = bets.getJSONArray(i);
            				
            				
            				
            				String checkBetTimestr = bet.getString(5);
            				
            				long timeL = df.parse(checkBetTimestr).getTime() + 12*60*60*1000;
            				
            				if(Math.abs(timeL - time) <= 2000) {
            					resmap.put("wagerId", Long.toString(bet.getLong(0)));
            	            	//resmap.put("eventId", resjb.getString("selectionId").split("\\|")[7]);
            	            	resmap.put("ratio", bet.getString(7));
            	            	
            	            	if(bet.getString(11).equals("OPEN")) {
            	            		
                	            	resmap.put("status", "1");
                	            	resmap.put("bettime", df.format(timeL));
                	            	return resmap;
                	            	
            	            	}else if(bet.getString(11).contains("PENDING")) {
            	            		resmap.put("status", "0");
                	            	
                	            	resmap.put("bettime", df.format(timeL));
                	            	
                	            	return resmap;
            	            	}

            				}

            			}
            			
            	resmap.put("status", "-1");
            	return resmap;
            	
            	
            }else {
            	return null;
            }
    		
    	}catch(Exception e) {    		
    		System.out.println(df.format(System.currentTimeMillis()) + "requestTimeoutBetCheck  ps38比赛状态未确认:");
    		e.printStackTrace();    		
    		return null;
    	}
		
	}
	
	
	
	public void getGameResult() {
		
    	try{    		
    		String dataStr = getOutlineData("0");    	
    		
    		canGetGameResultTime = System.currentTimeMillis() + 3*60*60*1000;
    		
			if(dataStr != null) {
				JSONArray ja = new JSONArray(dataStr);

				
				for(int i = 0; i < ja.length(); i++) {
					
					JSONArray ja1 = ja.getJSONArray(i);


					
					if(ja1.getString(3).equals("OPEN_BAL")) {
						continue;
					}else if(ja1.getString(3).equals("BETTING")) {

						
						String date = ja1.getString(0);
						String res = getDetailsData(date);
						Common.logOut("更新PS38比分");
        				
						NegativeRatioClient.betCtrMng.updateBetAdyGameResultUsePs38(res);
					}


				}
			}

    	}catch(Exception e){
    		e.printStackTrace();

    	}
		
	}
	
	
	public String getOutlineData(String count) {
		try {
			
			//Vector<Event> ps38Events = new Vector<Event>();
			
			
	    	//SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");// 设置日期格式
	    	SimpleDateFormat df = new SimpleDateFormat("dd/MM/yyyy");// 设置日期格式
	    	
	    	long currentTimeMillis = System.currentTimeMillis();
	    	
	    	Calendar currentTime = Calendar.getInstance();
	    	currentTime.add(Calendar.HOUR_OF_DAY, -12);
	    	
	    	//https://www.ps3838.com/member-service/v1/statement2?wallet=SB&date=MONTH&count=0&fromDate=17%2F02%2F2020&toDate=17%2F02%2F2020&_=1581989027137&locale=zh_CN
	    	
	    	String oduri = ADDRESS + "member-service/v2/statement2?wallet=SB&date=MONTH&count=" + count + "&fromDate=" + df.format(currentTime.getTimeInMillis()) + 
	    			"&toDate=" + df.format(currentTime.getTimeInMillis()) +"&_=" + currentTimeMillis + "&locale=zh_CN";
	    	
	        HttpRequest request = HttpRequest
	                //.newBuilder(URI.create("http://hga020.com/"))
	                .newBuilder(URI.create(oduri))
	                //.header("Host", "www.ps3838.com")//携带的参数
	                
	                .header("Accept-Encoding", "")
	                .header("Referer", "https://www.ps3838.com/zh-cn/sports")
	                .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
	                .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
	                .header("Accept", "application/json, text/javascript, */*; q=0.01")
	                .header("X-Requested-With", "XMLHttpRequest")
	                .version(Version.HTTP_2)
	                .timeout(Duration.ofSeconds(20))//2秒过期
	                .GET()
	                .build();
	        
	        
	        
	        if(hasLang == false) {
	            HttpCookie cookie1 = new HttpCookie("skin", "ps3838");
	            cookie1.setDomain(".ps3838.com");
	            cookie1.setPath("/");
	            cookie1.setVersion(0);
	            
	            HttpCookie cookie2 = new HttpCookie("lang", "zh_CN");
	            cookie2.setDomain(".ps3838.com");
	            cookie2.setPath("/");
	            cookie2.setVersion(0);
	            
	            cookieManager.getCookieStore().add(null, cookie1);
	            cookieManager.getCookieStore().add(null, cookie2);
	            
	            hasLang = true;
	        }
	        
	        
	        String res = getReponse(request);
	        
	        if(res.equals("")) {
	        	res = getReponse(request);
	        }

	        if(res.toLowerCase().contains("name=\"robots\"")) {
	        	updateStatusCode(0);
	        	return null;
	        }
	        
	        
	        if(!res.contains("Main Wallet")) {
	        	
	        	Common.logOut("获取" + res);
	        	
	        	return null;
	        }
	        
	        return res;
	        //return getMatches(res, homeTeam, awayTeam);
	        
	        
			
		}catch(Exception e) {
			e.printStackTrace();
		}
		
		
		return null;
	}


	public String getDetailsData(String datetime) {
		//Vector<Event> ps38Events = new Vector<Event>();
		try {
		
        	String paramstr = "f=" + datetime + "&t=" + datetime + "&d=0&s=SETTLED&sd=true&type=STATEMENT&product=SB";
        	
        	
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(ADDRESS + "member-service/v2/wager-filter?locale=zh_CN"))
                    .header("Content-Type","application/x-www-form-urlencoded")
                    .header("Accept-Encoding", "")
                    .header("Connection", "keep-alive")
                    .header("User-Agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0")
                    .header("Accept-Language", "zh-CN,zh;q=0.8,zh-TW;q=0.7,zh-HK;q=0.5,en-US;q=0.3,en;q=0.2")
                    .header("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
                    .header("Referer", "https://www.ps3838.com/zh-cn/")
                    .header("Host", "www.ps3838.com")
                    .version(Version.HTTP_2)
                    .timeout(Duration.ofSeconds(10))//2秒过期
                    .POST(HttpRequest.BodyPublisher.fromString(paramstr))
                    .build();
	        
	        
	        
	       
	        
	        
	        String res = getReponse(request);
	        
	        if(res.equals("")) {
	        	res = getReponse(request);
	        }
	
	        if(res.toLowerCase().contains("name=\"robots\"")) {
	        	updateStatusCode(0);
	        	return null;
	        }
	        
	        
	        if(!res.contains(datetime)) {
	        	
	        	Common.logOut("获取" + res);
	        	
	        	return null;
	        }
	        
	        return res;
	        //return getMatches(res, homeTeam, awayTeam);
        
        
		
	}catch(Exception e) {
		e.printStackTrace();
	}
	
	
	return null;
	}

}
